<template>
  <div class="relative inline-block text-left mr-3 sm:mr-0"
    ref="language">
    <div class="languageSelect">
      <button type="button"
        class="dropdown inline-flex w-full justify-center items-center rounded-md  bg-white py-2 text-base font-medium text-gray-1000 hover:text-purple-1300 noBg to-show-lang"
        :class="{'px-4':hasBorder, 'border':hasBorder, 'border-gray-1300':hasBorder,'shadow-sm':hasBorder}"
        aria-expanded="true"
        aria-haspopup="true"
        @click="showOptions">
        <svg-icon iconName='language_default'
          :isDiv="true"
          className="icon-language"></svg-icon>
        <span class="whitespace-nowrap truncate ml-2 uppercase"> {{$store.state.locale}}</span>
        <svg class="-mr-1 ml-2 h-5 w-5"
          viewBox="0 0 20 20"
          fill="currentColor"
          aria-hidden="true"
          :class="{show:isShowOptions}">
          <path fill-rule="evenodd"
            d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z"
            clip-rule="evenodd" />
        </svg>
      </button>
    </div>

    <div class="absolute left-0 z-10 mt-2 min-w-full origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none optionsMax"
      role="menu"
      aria-orientation="vertical"
      tabindex="-1"
      v-if="isShowOptions"
      :style="{ maxHeight: maxHeight,transform:isOther ? `translateY(${transY})`:'translateY(0)',marginTop:isOther ? '-20px':'8px' }">
      <div class="py-1 overflow-y-auto"
        role="none"
        :key="locale">
        <template>
          <nuxt-link v-for="(item,key) in languagesOptions"
            no-prefetch
            :prefetch="false"
            :key="key"
            event=""
            :to="{path: locale === 'en' ? (item.value==='en' ? $route.fullPath:`/${item.value}${$route.fullPath}`):(item.value==='en' ? ($route.fullPath.startsWith(`/${locale}/`) ? $route.fullPath.replace(`/${locale}`,''):$route.fullPath.replace(`/${locale}`,'/')):$route.fullPath.replace(`/${locale}`,`/${item.value}`))}"
            class="text-gray-1000 block px-4 py-2 text-sm duration-100 hover:text-purple-1300 whitespace-nowrap to-change-lang"
            :class="{'text-purple-1300': item.value === locale,'font-semibold': item.value === locale,'hover:opacity-90': item.value === locale }"
            @click.stop.native.prevent="beforeChange(item.value)">
            {{item.label}}
          </nuxt-link>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'CommonLanguage',
  props: {
    //是否有边框
    hasBorder: {
      type: Boolean,
      default: true,
      isOther: false,
      transY: 0,
    },

    isFooter: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    ...mapState({
      languagesOptions: (state) => state.languagesOptions,
      locale: (state) => state.locale,
    }),
  },
  data() {
    return {
      isShowOptions: false,
      maxHeight: '60vh',
      isOther: false,
      transY: null,
    }
  },
  filters: {
    fLocale: function (val, languagesOptions) {
      let res = languagesOptions.find((item) => {
        return item.value === val
      })
      if (res) {
        return res.label
      } else {
        return '-'
      }
    },
  },
  watch: {
    locale(val) {
      this.$i18n.locale = val
    },
    $route: {
      handler(val) {
        this.isShowOptions = false
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    document.addEventListener('click', this.handleClick)
  },
  methods: {
    ...mapMutations(['SET_LANG']),
    handleClick(event) {
      var target = event.target
      if (this.$refs.language) {
        let self = this.$refs.language.contains(target)
        if (!self) {
          this.isShowOptions = false
        }
      }
    },

    showOptions() {
      this.isShowOptions = !this.isShowOptions
      this.$nextTick(() => {
        if (this.isShowOptions) {
          let windowHeight =
            document.documentElement.clientHeight || document.body.clientHeight
          let langHeight = 0
          let langTop = 0
          langHeight = document.querySelector('.languageSelect').offsetHeight
          langTop = document
            .querySelector('.languageSelect')
            .getBoundingClientRect().top

          if (
            langHeight === 0 &&
            document.querySelectorAll('.languageSelect').length >= 2
          ) {
            langHeight =
              document.querySelectorAll('.languageSelect')[1].offsetHeight
            langTop = document
              .querySelectorAll('.languageSelect')[1]
              .getBoundingClientRect().top
          }

          if (
            this.isFooter &&
            document.querySelectorAll('.languageSelect').length >= 3
          ) {
            langHeight =
              document.querySelectorAll('.languageSelect')[2].offsetHeight
            langTop = document
              .querySelectorAll('.languageSelect')[2]
              .getBoundingClientRect().top
          }

          if (
            this.$route.name !== 'lang-login' &&
            this.$route.name !== 'lang-register' &&
            this.$route.name !== 'login' &&
            this.$route.name !== 'register' &&
            !this.isFooter
          ) {
            this.isOther = false
            this.maxHeight = `${windowHeight - langHeight - langTop - 20}px`
          } else {
            let offsetHeight =
              document.querySelector('.optionsMax').offsetHeight

            if (this.isFooter) {
              offsetHeight =
                document.querySelectorAll('.optionsMax')[
                  document.querySelectorAll('.optionsMax').length - 1
                ].offsetHeight
            }
            this.isOther = true
            this.transY = `-${offsetHeight + langHeight + 10}px`
          }
        }
      })
    },

    beforeChange(val) {
      let path =
        this.locale === 'en'
          ? val === 'en'
            ? this.$route.fullPath
            : `/${val}${this.$route.fullPath}`
          : val === 'en'
          ? this.$route.fullPath.startsWith(`/${this.locale}/`)
            ? this.$route.fullPath.replace(`/${this.locale}`, '')
            : this.$route.fullPath.replace(`/${this.locale}`, '/')
          : this.$route.fullPath.replace(`/${this.locale}`, `/${val}`)

      this.$cookies.set('locale', val, {
        maxAge: 60 * 60 * 24 * 365,
        path: '/',
      })

      this.$router.push({
        path: path,
      })
    },
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleClick)
  },
}
</script>
<style lang='scss' scoped>
.dropdown {
  svg {
    transition: 0.2s;
    &.show {
      transform: rotate(180deg);
    }
  }
}
.icon-language {
  font-size: 22px;
}
</style>
